<template>
  <div class="typical-rainfall-container">
    <!-- 统计概览 -->
    <el-row :gutter="20" class="statistics-overview">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32" color="#409eff"><Drizzling /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.totalRainfall }}</div>
              <div class="stat-label">总降雨量(mm)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32" color="#67c23a"><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.rainyDays }}</div>
              <div class="stat-label">降雨天数(天)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32" color="#e6a23c"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.avgRainfall }}</div>
              <div class="stat-label">平均降雨量(mm)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32" color="#f56c6c"><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.heavyRainDays }}</div>
              <div class="stat-label">暴雨天数(天)</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="降雨类型">
          <el-select
            v-model="queryForm.rainfallType"
            placeholder="请选择降雨类型"
            clearable
            style="width: 150px"
          >
            <el-option label="小雨" value="小雨" />
            <el-option label="中雨" value="中雨" />
            <el-option label="大雨" value="大雨" />
            <el-option label="暴雨" value="暴雨" />
            <el-option label="大暴雨" value="大暴雨" />
            <el-option label="特大暴雨" value="特大暴雨" />
          </el-select>
        </el-form-item>
        <el-form-item label="监测站点">
          <el-select
            v-model="queryForm.stationId"
            placeholder="请选择监测站点"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="station in rainfallStations"
              :key="station.id"
              :label="station.name"
              :value="station.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="降雨量范围">
          <el-input
            v-model="queryForm.minRainfall"
            placeholder="最小值"
            style="width: 100px"
          />
          <span style="margin: 0 10px">-</span>
          <el-input
            v-model="queryForm.maxRainfall"
            placeholder="最大值"
            style="width: 100px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增记录
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="warning" @click="handleViewChart">
          <el-icon><TrendCharts /></el-icon>
          统计图表
        </el-button>
        <el-button type="info" @click="handleAnalysis">
          <el-icon><DataAnalysis /></el-icon>
          数据分析
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="stationName" label="监测站点" width="120" />
        <el-table-column prop="rainfallDate" label="降雨日期" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="120" />
        <el-table-column prop="endTime" label="结束时间" width="120" />
        <el-table-column prop="duration" label="持续时长(h)" width="100" />
        <el-table-column prop="totalRainfall" label="总降雨量(mm)" width="120" />
        <el-table-column prop="maxIntensity" label="最大强度(mm/h)" width="120" />
        <el-table-column prop="rainfallType" label="降雨类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getRainfallTagType(row.rainfallType)">
              {{ row.rainfallType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTypical" label="是否典型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isTypical ? 'success' : 'info'">
              {{ row.isTypical ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="weatherCondition" label="天气状况" width="100" />
        <el-table-column prop="recordPerson" label="记录人" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="warning" icon="Document" @click="handleViewDetail(row)">详情</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <TypicalRainfallFormDialog
      v-model:visible="formDialogVisible"
      :form-data="currentFormData"
      :is-view="isView"
      @success="handleFormSuccess"
    />

    <!-- 详情弹窗 -->
    <RainfallDetailDialog
      v-model:visible="detailDialogVisible"
      :detail-data="currentDetailData"
    />

    <!-- 图表弹窗 -->
    <RainfallChartDialog
      v-model:visible="chartDialogVisible"
      :chart-data="tableData"
    />

    <!-- 分析弹窗 -->
    <RainfallAnalysisDialog
      v-model:visible="analysisDialogVisible"
      :analysis-data="tableData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Delete, 
  Download, 
  TrendCharts,
  DataAnalysis,
  Drizzling,
  Calendar,
  Warning
} from '@element-plus/icons-vue'
import TypicalRainfallFormDialog from './components/TypicalRainfallFormDialog.vue'
import RainfallDetailDialog from './components/RainfallDetailDialog.vue'
import RainfallChartDialog from './components/RainfallChartDialog.vue'
import RainfallAnalysisDialog from './components/RainfallAnalysisDialog.vue'

// 统计概览
const overview = reactive({
  totalRainfall: 1256.8,
  rainyDays: 45,
  avgRainfall: 27.9,
  heavyRainDays: 8
})

// 监测站点
const rainfallStations = ref([
  { id: 1, name: '西音水库主站' },
  { id: 2, name: '大坝监测站' },
  { id: 3, name: '库区中心站' },
  { id: 4, name: '入库口站' },
  { id: 5, name: '出库口站' },
  { id: 6, name: '上游监测站' },
  { id: 7, name: '下游监测站' }
])

// 查询表单
const queryForm = reactive({
  rainfallType: '',
  stationId: '',
  dateRange: [],
  minRainfall: '',
  maxRainfall: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗控制
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const chartDialogVisible = ref(false)
const analysisDialogVisible = ref(false)
const currentFormData = ref(null)
const currentDetailData = ref(null)
const isView = ref(false)

// 获取降雨类型标签样式
const getRainfallTagType = (type: string) => {
  const typeMap = {
    '小雨': 'success',
    '中雨': 'primary',
    '大雨': 'warning',
    '暴雨': 'danger',
    '大暴雨': 'danger',
    '特大暴雨': 'danger'
  }
  return typeMap[type] || ''
}

// 模拟API - 获取典型降雨列表
const fetchRainfallListLegacy = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const mockData = [
      {
        id: 1,
        stationName: '西音水库主站',
        rainfallDate: '2024-01-15',
        startTime: '14:30',
        endTime: '18:45',
        duration: 4.25,
        totalRainfall: 85.6,
        maxIntensity: 32.5,
        rainfallType: '暴雨',
        isTypical: true,
        weatherCondition: '雷阵雨',
        recordPerson: '张三',
        remark: '典型暴雨过程，伴有雷电'
      },
      {
        id: 2,
        stationName: '大坝监测站',
        rainfallDate: '2024-01-12',
        startTime: '09:15',
        endTime: '15:30',
        duration: 6.25,
        totalRainfall: 45.2,
        maxIntensity: 18.3,
        rainfallType: '大雨',
        isTypical: true,
        weatherCondition: '阴雨',
        recordPerson: '李四',
        remark: '持续性降雨'
      },
      {
        id: 3,
        stationName: '库区中心站',
        rainfallDate: '2024-01-10',
        startTime: '20:00',
        endTime: '23:15',
        duration: 3.25,
        totalRainfall: 28.7,
        maxIntensity: 15.2,
        rainfallType: '中雨',
        isTypical: false,
        weatherCondition: '小雨',
        recordPerson: '王五',
        remark: '夜间降雨'
      },
      {
        id: 4,
        stationName: '入库口站',
        rainfallDate: '2024-01-08',
        startTime: '06:45',
        endTime: '12:20',
        duration: 5.58,
        totalRainfall: 125.3,
        maxIntensity: 45.8,
        rainfallType: '大暴雨',
        isTypical: true,
        weatherCondition: '暴雨',
        recordPerson: '赵六',
        remark: '特大暴雨过程，需重点关注'
      },
      {
        id: 5,
        stationName: '出库口站',
        rainfallDate: '2024-01-05',
        startTime: '16:20',
        endTime: '19:45',
        duration: 3.42,
        totalRainfall: 15.8,
        maxIntensity: 8.5,
        rainfallType: '小雨',
        isTypical: false,
        weatherCondition: '多云转雨',
        recordPerson: '孙七',
        remark: '轻微降雨'
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取降雨数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除降雨记录
const deleteRainfallRecordLegacy = async (ids: number[]) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('删除成功')
    fetchRainfallList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 导出数据
const exportRainfallData = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查询
const handleQueryLegacy = () => {
  pagination.currentPage = 1
  fetchRainfallList()
}

// 重置
const handleResetLegacy = () => {
  Object.assign(queryForm, {
    rainfallType: '',
    stationId: '',
    dateRange: [],
    minRainfall: '',
    maxRainfall: ''
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentFormData.value = null
  isView.value = false
  formDialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentFormData.value = { ...row }
  isView.value = true
  formDialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentFormData.value = { ...row }
  isView.value = false
  formDialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row: any) => {
  currentDetailData.value = { ...row }
  detailDialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除"${row.stationName}"在"${row.rainfallDate}"的降雨记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteRainfallRecord([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 条降雨记录吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteRainfallRecord(selectedIds.value)
  })
}

// 导出
const handleExport = () => {
  exportRainfallData()
}

// 查看图表
const handleViewChart = () => {
  chartDialogVisible.value = true
}

// 数据分析
const handleAnalysis = () => {
  analysisDialogVisible.value = true
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增：统一数据源与筛选分页工具
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)]

const generateMockData = (count: number) => {
  const stations = rainfallStations.value.map(s => s.name)
  const types = ['小雨', '中雨', '大雨', '暴雨', '大暴雨', '特大暴雨']
  const weathers = ['晴', '多云', '阴', '小雨', '中雨', '大雨', '暴雨']
  const persons = ['张三', '李四', '王五', '赵六', '孙七']
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const stationName = randomChoice(stations)
    const m = randInt(1, 12)
    const d = randInt(1, 28)
    const rainfallDate = `${2024}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`
    const startHour = randInt(0, 23)
    const startMin = randInt(0, 59)
    const duration = +(Math.random() * 6 + 0.5).toFixed(2)
    const totalRainfall = +(Math.random() * 150 + 5).toFixed(1)
    const maxIntensity = +(Math.random() * 60 + 1).toFixed(1)
    const rainfallType = randomChoice(types)
    const isTypical = Math.random() < 0.5
    const weatherCondition = randomChoice(weathers)
    const recordPerson = randomChoice(persons)
    const startTime = `${String(startHour).padStart(2, '0')}:${String(startMin).padStart(2, '0')}`
    const endHour = (startHour + Math.max(1, Math.floor(duration))) % 24
    const endTime = `${String(endHour).padStart(2, '0')}:${String(startMin).padStart(2, '0')}`
    list.push({
      id: i + 1,
      stationName,
      rainfallDate,
      startTime,
      endTime,
      duration,
      totalRainfall,
      maxIntensity,
      rainfallType,
      isTypical,
      weatherCondition,
      recordPerson,
      remark: '模拟记录'
    })
  }
  return list
}

const applyFiltersAndPaginate = () => {
  let filtered = allData.value.slice()
  if (queryForm.rainfallType) {
    filtered = filtered.filter(item => item.rainfallType === queryForm.rainfallType)
  }
  if (queryForm.stationId) {
    const station = rainfallStations.value.find(s => s.id === queryForm.stationId)
    if (station) {
      filtered = filtered.filter(item => item.stationName === station.name)
    }
  }
  if (Array.isArray(queryForm.dateRange) && queryForm.dateRange.length === 2 && queryForm.dateRange[0] && queryForm.dateRange[1]) {
    const [start, end] = queryForm.dateRange as [string, string]
    const startTime = new Date(start).getTime()
    const endTime = new Date(end).getTime()
    filtered = filtered.filter(item => {
      const t = new Date(item.rainfallDate).getTime()
      return t >= startTime && t <= endTime
    })
  }
  const min = Number(queryForm.minRainfall)
  if (queryForm.minRainfall !== '' && !Number.isNaN(min)) {
    filtered = filtered.filter(item => item.totalRainfall >= min)
  }
  const max = Number(queryForm.maxRainfall)
  if (queryForm.maxRainfall !== '' && !Number.isNaN(max)) {
    filtered = filtered.filter(item => item.totalRainfall <= max)
  }
  pagination.total = filtered.length
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  tableData.value = filtered.slice(startIndex, startIndex + pagination.pageSize)
}

// 修补：获取列表使用模拟源与筛选分页
const fetchRainfallList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    if (!allData.value.length) {
      allData.value = generateMockData(randInt(10, 50))
    }
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取降雨数据失败')
  } finally {
    loading.value = false
  }
}

// 修补：删除记录直接更新数据源并分页
const deleteRainfallRecord = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    applyFiltersAndPaginate()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    rainfallType: '',
    stationId: '',
    dateRange: [],
    minRainfall: '',
    maxRainfall: ''
  })
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  applyFiltersAndPaginate()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  applyFiltersAndPaginate()
}

// 表单成功回调
const handleFormSuccess = () => {
  fetchRainfallList()
}

// 初始化
onMounted(() => {
  fetchRainfallList()
})
</script>

<style scoped>
.typical-rainfall-container {
  padding: 20px;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 15px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>